//index.js
//获取应用实例
var app = getApp();
var time_go = '';

Page({

	data: {
		urlimg: app.urlimg,
		order: null,
		selectIndex: null,
    listItem: ["全部", "待付款", "待成团", "待开奖", "待发货", '待收货', '待评价', '已完成',],
    // listItem: ["全部", "待付款", "待成团", "待开奖", "待发货", '待收货', '待评价', '已完成', '退款售后'],
		data: {},
		defaultpages: "2",
		loadHidden: true,
		loadText: "加载中...",
		msg: '没有更多订单了',
		toastHidden: true,
		loading_ing: true,
    // 显示猜你喜欢列表
    love_goods:true,
	},
	onShow: function (s) {
		var that = this;
		countdown(that);
		if (that.data.selectIndex == null) return;
	},
	onLoad: function (o) {
		var that = this;


    app.app_load(load_fn);

    function load_fn() {
		if (o.fid) {
			var index = o.fid;
			/*if(index==3||index==4){
				index=2
			} else if (index == 5) {
				index = 3
			}*/
			that.setData({
				selectIndex: index,
        order: (that.data.data.order ? that.data.data.order : '0'),
			})
		}
    that.getData();
    //猜你喜欢
    wx.request({
      url: app.url + 'api_footprint/footprint_group_list',
      data: {
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      },
      success: function (json) {
        that.setData({
          likegoods: json.data.result,
        })
      }
    })
    }
	},

  // 猜你喜欢列表
  click_goods: function (e) {
    wx.navigateTo({
      url: '/pages/index/detail/index?id=' + e.currentTarget.id,
    })
  },

	getData: function () {
		var that = this;
		wx.request({
			url: app.url + 'api_user/orderV1',
			data: {
				status: that.data.selectIndex
			},
			header: {
				'content-type': 'application/json',
				'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        wx.hideLoading();
				console.log(json.data.result);
				if (json.data.done == true) {
					//倒计时
					var data = json.data.result;
					if (data.length>0){
						for (var i = 0; i < data.length; i++) {
							data[i].countdown = '';
							data[i].str_create_time += 86400;
							time_computations(data[i].str_create_time , i,data, that)
						}
					}

					that.setData({ data: data, loadHidden: true })
				} else {
					wx.showModal({
						title: '提示',
						content: json.data.message,
					})
				}
			}, complete: function (json) {

			}
		})
	},
	//延长收货
	extend_receipt:function(e){
		var that=this;
		wx.showModal({
			title: '提示',
			content: '每张订单延长收货只能申请一次，延长收货时间为5天。',
			success: function (res) {
				if (res.confirm) {
					console.log('获取订单id为：'+e.currentTarget.id);
					wx.request({
						url: app.url + 'api_order/extendTime',
						data: { orderId: e.currentTarget.id},
						header: {
							'content-type': 'application/json',
							'token': wx.getStorageSync('token_key')
						},
						success: function(res) {
							var all_box=that.data.data;
							for (var i = 0; i < all_box.length;i++){
								if(all_box[i].id == e.currentTarget.id){
									all_box[i].is_extend=1;
								}
							}
							that.setData({
								data:all_box,
							})
							//提示信息
							wx.showToast({
								title: '成功延长收货',
								icon: 'success',
								duration: 1500,
							})
						},
					})
				}
			}
		})
	},
	// 响应订单状态(头部点击)
	itemTAP: function (e) {
		var that = this;
		var index = e.currentTarget.id;
		console.log(index)

		that.setData({
			selectIndex: index,
      loadHidden: false,
			scrollTop: 0,
      love_goods: true
		})
		if (index == 1 || index == 3) {
			that.setData({
				order: null,
			})
		} else {
			that.setData({
        order: (that.data.data.order ? that.data.data.order : '0'),
			})
		}
		wx.request({
			url: app.url + 'api_user/orderV1',
			data: {
				status: index
			},
			header: {
				'content-type': 'application/json',
				'token': wx.getStorageSync('token_key')
			}, success: function (json) {
        console.log(json.data);
        if (json.data.done == true) {
          console.log(json.data.result);
          var data = json.data.result;
          if (data.length < 5) { that.setData({ love_goods: false })}
          that.setData({ data: data, loadHidden: true })
					if (data.length > 0) {
						for (var i = 0; i < data.length; i++) {
							data[i].countdown = '';
							data[i].str_create_time += 86400;
							time_computations(data[i].str_create_time, i, data, that)
						}
					}
				} else {
					wx.showModal({
						title: '提示',
						content: json.data.message
					})
				}
			}
		})
	},
	// 评论
	commentTap: function (e) {

		let gid = e.currentTarget.dataset.gid;
		let id = e.currentTarget.id;

    /*wx.navigateTo({
      url: '/pages/account/comment/index?sn='+sn+'&id='+id,
    })*/
		wx.navigateTo({
			url: '/pages/account/submit/index?order_id=' + id + '&gid=' + gid,
		})
	}
	,
	again_buy_btn: function (e) {
		wx.redirectTo({
			url: '/pages/index/detail/index?id=' + e.currentTarget.id,
		})
	},
	//退款申请
	refunds: function (e) {
		console.log(e.currentTarget.dataset.id);
		console.log(e.currentTarget.dataset.order_id);
		wx.redirectTo({
			url: '/pages/account/refund/index?order_goods_id='
			+ e.currentTarget.dataset.id + '&order_id='
			+ e.currentTarget.dataset.order_id
		})
	},
	//邀请好友拼团
	invite: function (e) {
		var order_id = e.currentTarget.dataset.order_id
		if (order_id > 0) {
			wx.navigateTo({
				url: '/pages/mygroup/invite/invite?orderId=' + order_id,
			})
		}
	},
	//查看中奖详情
	is_prize: function (e) {
		var order_id = e.currentTarget.dataset.order_id
		if (order_id > 0) {
			wx.navigateTo({
				url: '/pages/mygroup/winning/winning?orderId=' + order_id,
			})
		}
	},
	//查看物流信息
	show_delivery_btn: function (e) {
		if(e.currentTarget.dataset.type==2){
		//多条快递信息
      wx.redirectTo({url: '/pages/account/order/logistics/index?id=' + e.currentTarget.id,})
		}else{
			wx.navigateTo({url: '/pages/account/logistics/index?order_id=' + e.currentTarget.id+ '&id=0',})
		}
	},



	// 响应订单被单击
	orderTAP: function (e) {
		this.setData({
			defaultpages: "2",
		});
		wx.navigateTo({
			url: '/pages/account/orderDetail/index?id=' + e.currentTarget.id,
		})
	},
	reminder_distribution: function (e) {
		var that = this;
		wx.request({
			url: app.url + 'api_user/reminder_distribution',
			data: {
				order_id: e.currentTarget.id,
			},
			header: {
				'content-type': 'application/json',
				'token': wx.getStorageSync('token_key')
			}, success: function (json) {
				if (json.data.done == true) {
					var newdata = that.data.data;
					for (var i = 0; i < newdata.length; i++) {
						if (newdata[i].id == e.currentTarget.id) {
							newdata[i].reminder_distribution = 1
						}
					}
					that.setData({ data: newdata })
				} else {
					wx.showModal({
						title: '提示',
						content: json.data.message,
					})
				}
			}
		})
	},
	doneOrder: function (e) {
		wx.redirectTo({
			url: '/pages/account/orderDetail/index?id=' + e.currentTarget.id,
		})
	},
	cancel: function (e) {
		var that = this;
		wx.showModal({
			title: '提示',
			content: '确定取消订单？',
			success: function (res) {
				if (res.confirm) {
					wx.request({
						url: app.url + 'api_user/order_status',
						data: {
							order_id: e.currentTarget.id,
							op: 'cancel'
						},
						header: {
							'content-type': 'application/json',
							'token': wx.getStorageSync('token_key')
						}, success: function (json) {
							if (json.data.done == true) {
								that.getData();

							} else {
								wx.showModal({
									title: '提示',
									content: json.data.message,
								})
							}
						}
					})
				}
			}
		})


	},
  //搜索框
  search:function(e){
    var that = this;
    console.log(that.data.index);
    console.log(e.detail.value.input);
    var keyword='';
    if (e.detail.value.input){
      keyword =e.detail.value.input;
    }
    wx.request({
      url: app.url + 'api_user/orderV1',
      data: {
        status: that.data.index,
        keyword: keyword,
      },
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token_key')
      }, success: function (json) {
        console.log(json.data);
        if (json.data.done == true) {
          console.log(json.data.result);
          var data = json.data.result;
          that.setData({ data: data, loadHidden: true, keyword: keyword, })
          if (data.length > 0) {
            for (var i = 0; i < data.length; i++) {
              data[i].countdown = '';
              data[i].str_create_time += 86400;
              time_computations(data[i].str_create_time, i, data, that)
            }
          }
        } else {
          wx.showModal({
            title: '提示',
            content: json.data.message
          })
        }
      }
    })
    that.setData({scrollTop: 0,});
    
    console.log(e.detail.value.input);
  },
	//下拉加载下一页
	onReachBottom: function () {
		var page = this;
		wx.hideNavigationBarLoading() //完成停止加载
		if (page.data.loading_ing) {
      console.log("请求加载");
			page.setData({ loadHidden: false, loading_ing: false })
      var keyword = page.data.keyword;
      if (keyword==undefined){
        keyword='';
      }
			//判断是全部还是默认
			var forumPage = page.data.defaultpages
			wx.request({
				url: app.url + 'api_user/orderV1',
				data: {
					status: page.data.selectIndex,
					page: forumPage,
          keyword: keyword,
				},
				header: {
					'content-type': 'application/json',
					'token': wx.getStorageSync('token_key')
				},
        success: function (res) {
					console.log(res)
					if (res.data.done == true && res.data.result.length > 0) {
						var order = page.data.data;
						var newForum = order.concat(res.data.result);
						page.setData({ data: newForum, defaultpages: ++page.data.defaultpages });
					} else {
						page.setData({ love_goods: false })
						wx.showToast({
							title: page.data.msg,
							image: '/pages/icon/delete.png',
							duration: 1500,
						})
					}

          page.setData({ loading_ing: true });
				}, complete: function () {
					wx.hideNavigationBarLoading() //完成停止加载
					page.setData({ loadHidden: true })
				}

			})

		}

	},
	onPullDownRefresh: function () {
		wx.stopPullDownRefresh;
	},
	refund: function (e) {
		console.log(e)
		wx.redirectTo({
			url: '/pages/account/refund/index?id=' + e.currentTarget.id + "&type=" + e.target.dataset.type,
		})

	},
	//确认收货
	confirm: function (e) {
		var that = this;
		wx.showModal({
			title: '提示',
			content: '请收到货后，再确认收货！',
			success: function (res) {
				if (res.confirm) {
					wx.request({
						url: app.url + 'api_user/order_status',
						data: {
							order_id: e.currentTarget.id,
							op: 'confirm'
						},
						header: {
							'content-type': 'application/json',
							'token': wx.getStorageSync('token_key')
						}, success: function (json) {
							if (json.data.done == true) {
								that.getData();
							} else {
								wx.showModal({
									title: '提示',
									content: json.data.message,
								})
							}
						}
					})
				}
			}
		})
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {
		clearInterval(time_go);
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		clearInterval(time_go);
  },    
  //分享
  onShareAppMessage: function () {

  },

})


//倒计时函数
function countdown(that) {
	time_go = setInterval(function () {
		var data = that.data.data;
		if (data.length > 0) {
			for (var i = 0; i < data.length; i++) {
				time_computations(data[i].str_create_time, i, data, that)
			}
		}
	}, 1000);
};
//倒计时计算
function time_computations(Time, i, data, that) {
	var order_time = Time;
	var current_time = Date.parse(new Date()) / 1000;
	if (current_time < order_time) {
    var Times = order_time - current_time;
    --Times;
		var day = Math.floor(Times / (60 * 60 * 24));//计算剩余的天数
    if (('' + day).length == 1) {
      day = '0' + day;
    }
		var hours = parseInt(Times / 60 / 60 % 24, 10); //计算剩余的小时
		if (('' + hours).length == 1) {
			hours = '0' + hours;
		}
		var minutes = parseInt(Times / 60 % 60, 10);//计算剩余的分钟
		if (('' + minutes).length == 1) {
			minutes = '0' + minutes;
		}
		var seconds = parseInt(Times % 60, 10);//计算剩余的秒数
		if (('' + seconds).length == 1) {
			seconds = '0' + seconds;
		}
    //倒计时判断
    if (data[i].orderStatus==2){
      data[i].countdown = hours + "小时" + minutes + "分" + seconds + "秒";
    }else{
      data[i].countdown = day+'天'+ hours + "小时" + minutes + "分" + seconds + "秒";
    }
		// console.log(data[i].countdown);
		data[i].str_create_time = order_time;
	}else{
		data[i].countdown = '';
	} 
	that.setData({
		data: data,
	})
}